package com.service;

import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class MailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private  String from;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送邮件
     * @param to
     */
    public void sendMail(String to)
    {
        //产生验证码，并保存到redis
        String code = RandomUtil.randomString(4);
        //redisTemplate.boundValueOps(to).set(code,30, TimeUnit.MINUTES);
        //redisTemplate.boundValueOps(to).set(code);
        // redisTemplate.boundValueOps(to).expire(30,TimeUnit.MINUTES);
        redisTemplate.boundZSetOps("mail").add(to+":"+code,System.currentTimeMillis());

        //发送邮件
        SimpleMailMessage  message = new SimpleMailMessage();
        message.setFrom(from);  //发送者
        message.setTo(to);  //接收者
        message.setSubject("验证码注册"); //标题，主题

        message.setText("您的验证码是:"+code);  //内容

        javaMailSender.send(message);


    }

    /**
     *
     * @param mail  邮箱地址
     * @param code  验证码
     * @return true成功
     */
    public boolean checkCode(String mail, String code)
    {
        //从redis取出验证码
        BoundZSetOperations  zset = redisTemplate.boundZSetOps("mail");
        Long minchi = zset.rank(mail+":"+code);
        boolean f = minchi!=null;
        if (f)
        {
            //成功要删除原来的
            zset.removeRange(minchi,minchi);
            //redisTemplate.delete("mail");


        }


        return f;

    }

}
